package com.itboye.sunsun.web.ui;

import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsunhome.R;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ShiPinWebActivity extends Activity {

	private FrameLayout videoview;// 全屏时视频加载view
	private Button videolandport;
	private WebView videowebview;
	private Boolean islandport = true;//true表示此时是竖屏，false表示此时横屏。
	private View xCustomView;
	private xWebChromeClient xwebchromeclient;
	private String url;
	private WebChromeClient.CustomViewCallback 	xCustomViewCallback;
	
	
	private boolean backfirst = true;
	
	


	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);  
        if(VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {  
            Window window = getWindow();  
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN  
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);  
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
            window.setStatusBarColor(Color.TRANSPARENT);  
            window.setNavigationBarColor(Color.TRANSPARENT);  
        }  
		setContentView(R.layout.activity_shipinweb);
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		initwidget();
		initListener();
		url = getIntent().getStringExtra("url");
		videowebview.setHorizontalScrollBarEnabled(false);//水平不显示  
		videowebview.setVerticalScrollBarEnabled(false); //垂直不显示  
		System.out.println("video_webview"+url);
		videowebview.loadUrl(url);
		
	}

	

	private void initListener() {
		// TODO Auto-generated method stub
		videolandport.setOnClickListener(new Listener());
	}

	private void initwidget() {
		// TODO Auto-generated method stub
		videoview = (FrameLayout) findViewById(R.id.video_view);
		videolandport = (Button) findViewById(R.id.video_landport);
		videowebview = (WebView) findViewById(R.id.video_webview);
		WebSettings ws = videowebview.getSettings();
			videowebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		ws.setBuiltInZoomControls(true);// 隐藏缩放按钮
		ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
		ws.setUseWideViewPort(true);// 可任意比例缩放
		ws.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
		ws.setSavePassword(true);
		ws.setSaveFormData(true);// 保存表单数据
		ws.setJavaScriptEnabled(true);
//		ws.setGeolocationEnabled(true);// 启用地理定位
//		ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
		ws.setDomStorageEnabled(true);
		
		
		xwebchromeclient = new xWebChromeClient();
		videowebview.setWebChromeClient(xwebchromeclient);
		videowebview.setWebViewClient(new xWebViewClientent());
		
		videowebview.setOnKeyListener(new View.OnKeyListener() {      
		    @Override      
		    public boolean onKey(View v, int keyCode, KeyEvent event) {      
		        if (event.getAction() == KeyEvent.ACTION_DOWN) {  
		        	System.out.println("WebView返回keyCode "  + keyCode);
		            if (keyCode == KeyEvent.KEYCODE_BACK) {  //表示按返回键    
		            	System.out.println("WebView返回退出是不是全屏inCustomView " );
			    		
			            if (inCustomView()) {
			            	System.out.println("WebView返回退出是全屏");
			            	hideCustomView();
			            	return true;
			            }else {
			            	System.out.println("WebView返回退出不是全屏: " + backfirst);
			            	if(backfirst){
//				            		videowebview.loadUrl(url);  //by zss 
			            	videowebview.loadUrl(url);
			            		backfirst = false;
			            	}else{
			            		ShiPinWebActivity.this.finish();
			            	}
				   			 
//					   			 videowebview.loadUrl("about:blank");
//					   			 MainActivity.this.finish();
				       		 Log.i("testwebview", "===>>>2");
			            }
		            }      
		        }      
		        return false; 
		    }
		});
		
	}

	class Listener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.video_landport:
				if (islandport) {
					Log.i("testwebview", "竖屏切换到横屏");
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
					
					videolandport.setText("全屏不显示该按扭，点击切换竖屏");
				}else {

					Log.i("testwebview", "横屏切换到竖屏");
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
					videolandport.setText("全屏不显示该按扭，点击切换横屏");
				}
				break;

			default:
				break;
			}
		}
	}
	   @Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
		   if(Build.VERSION.SDK_INT < 19) {
			  System.out.println("WebView返回keyCode "  + keyCode);
	    	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    		System.out.println("WebView返回退出是不是全屏inCustomView " );
	    		
	            if (inCustomView()) {
	            	System.out.println("WebView返回退出是全屏");
	            	hideCustomView();
	            	return true;
	            }else {
	            	System.out.println("WebView返回退出不是全屏: " + backfirst);
	            	if(backfirst){
//	            		videowebview.loadUrl(url);  //by zss 
	            		videowebview.loadUrl(url);
	            		backfirst = false;
	            	}else{
	            		ShiPinWebActivity.this.finish();
	            	}
		   			 
//		   			 videowebview.loadUrl("about:blank");
//		   			 MainActivity.this.finish();
		       		 Log.i("testwebview", "===>>>2");
	            }
	    	}
		   }
	    	return false;  //不知道什么原因，return true竟然导致无法显示音量键调整音量，return false 就ok啦 add by zss 20160720
	    }
	   
	   
	   
	   /**
	    * 判断是否是全屏
	    * @return
	    */
	    public boolean inCustomView() {
	 		return (xCustomView != null);
	 	}
	     /**
	      * 全屏时按返加键执行退出全屏方法
	      */
	     public void hideCustomView() {
	    	 try {
	    		 System.out.println("WebView hideCustomView1");
	    		 xwebchromeclient.onHideCustomView();
	    		 System.out.println("WebView hideCustomView2");
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	 
	 	}
	/**
	 * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
	 */
	public class xWebChromeClient extends WebChromeClient {
		private Bitmap xdefaltvideo;
		private View xprogressvideo;
		@Override
    	//播放网络视频时全屏会被调用的方法
		public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
		{
			System.out.println("WebView onShowCustomView");
			if (islandport) {

			}
			else{
				
//				ii = "1";
//				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
			}
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
	        videowebview.setVisibility(View.GONE);
	        //如果一个视图已经存在，那么立刻终止并新建一个
	        if (xCustomView != null) {
	            callback.onCustomViewHidden();
	            return;
	        }
	        
	        videoview.addView(view);
	        xCustomView = view;
	        xCustomViewCallback = callback;
	        videoview.setVisibility(View.VISIBLE);
		}
		
		@Override
		//视频播放退出全屏会被调用的
		public void onHideCustomView() {
			System.out.println("WebView onHideCustomView开始");
			if (xCustomView == null)//不是全屏播放状态
				return;	       
			
			System.out.println("WebView onHideCustomView开始1");
			// Hide the custom view.
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
			
			xCustomView.setVisibility(View.GONE);
			// Remove the custom view from its container.
			videoview.removeView(xCustomView);
			xCustomView = null;
			videoview.setVisibility(View.GONE);
			xCustomViewCallback.onCustomViewHidden();
			
			videowebview.setVisibility(View.VISIBLE);
			
			System.out.println("WebView onHideCustomView结束");
			
	        //Log.i(LOGTAG, "set it to webVew");
		}
		
//		//视频加载添加默认图标
//		@Override
//		public Bitmap getDefaultVideoPoster() {
////			Log.i(LOGTAG, "here in on getDefaultVideoPoster");	
//			if (xdefaltvideo == null) {
//				xdefaltvideo = BitmapFactory.decodeResource(getResources(), R.drawable.videoicon);
//		    }
//			return xdefaltvideo;
//		}
		
		
		//视频加载时进程loading
		@Override
		public View getVideoLoadingProgressView() {
			//Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
			
	        if (xprogressvideo == null) {
	            LayoutInflater inflater = LayoutInflater.from(ShiPinWebActivity.this);
	            xprogressvideo = inflater.inflate(R.layout.video_loading_progress, null);
	        }
	        return xprogressvideo; 
		}
    	//网页标题
    	 @Override
         public void onReceivedTitle(WebView view, String title) {
            (ShiPinWebActivity.this).setTitle(title);
         }

//         @Override
//       //当WebView进度改变时更新窗口进度
//         public void onProgressChanged(WebView view, int newProgress) {
//        	 (MainActivity.this).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
//         }

	}

	/**
	 * 处理各种通知、请求等事件
	 */
	public class xWebViewClientent extends WebViewClient {

		 @Override
		    public boolean shouldOverrideUrlLoading(WebView view, String url) {
		    	Log.i("webviewtest", "shouldOverrideUrlLoading: "+url);
		    	backfirst = true;
		        return false;
		    }
		 
	}
	/**
	 * 当横竖屏切换时会调用该方法
	 */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	Log.i("testwebview", "=====<<<  onConfigurationChanged  >>>=====");
         super.onConfigurationChanged(newConfig);
         
         if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
             Log.i("webview", "   现在是横屏1");
             islandport = false;
            }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
             Log.i("webview", "   现在是竖屏1");
             islandport = true;
            }
    }
    
    @Override
    public void onResume() {
    	System.out.println("webView onResume");
    	
       
        try {
        	if(videowebview != null){
        		videowebview.getClass().getMethod("onResume").invoke(videowebview,(Object[])null);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		 super.onResume();
    }

    @Override
    public void onPause() {
    	System.out.println("webView onPause");
    	
        
        try {
        	if(videowebview != null){
        		videowebview.getClass().getMethod("onPause").invoke(videowebview,(Object[])null);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		super.onPause();
    }

	@Override
	protected void onDestroy() {
		System.out.println("webView onDestroy");
		if(videowebview != null){
			videowebview = null;
		}
		
		if(xCustomViewCallback != null){
			xCustomViewCallback = null;
		}
		
		super.onDestroy();
	}
    
    
}
